package rlyy.framework.netty.inithandler.strategy;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.method.HandlerMethod;
import rlyy.framework.core.common.enums.CommonEnum;
import rlyy.framework.core.common.exception.BaseRuntimeException;
import rlyy.framework.core.common.request.FullRequest;
import rlyy.framework.core.common.response.ResponseResult;
import rlyy.framework.core.common.response.ResultUtil;
import rlyy.framework.core.expand.IExecuteBeforeAndAfterBusinessProcessor;
import rlyy.framework.core.maping.RequestHandlerMapping;
import rlyy.framework.core.resolver.ParameterParsing;
import rlyy.framework.core.resolver.exception.MyExceptionHandlerExceptionResolver;
import rlyy.framework.netty.inithandler.HttpServerHandler;
import rlyy.framework.netty.support.DefaultParameterConversion;

import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 处理Netty请求处理器
 *
 * @author yuanqinglong
 * @since 2020/11/11 9:42
 */
@Component
public class NettyRequestProcess implements IRequestProcess {

    static final Logger logger = LoggerFactory.getLogger(NettyRequestProcess.class);

    @Autowired
    private RequestHandlerMapping requestMappingInitialize;

    /**
     * 调用方配置的请求方式、不配置Netty默认处理POST请求
     */
    @Autowired
    private RequestMethodConfiguration requestMethodConfiguration;

    @Autowired
    private MyExceptionHandlerExceptionResolver exceptionResolver;

    @Autowired
    private ParameterParsing parameterParsing;

    /**
     * 自定义的处理业务逻辑之前处理
     */
    @Autowired(required = false)
    private List<IExecuteBeforeAndAfterBusinessProcessor> iExecuteBeforeAndAfterBusinessProcessors;


    /**
     * 根据配置判断是否是Netty类处理的请求
     *
     * @param request 请求信息 判断此请求的请求方式(POST、GET、PUT、DELETE。。。)
     * @return true OR false
     */
    @Override
    public boolean supportsHandler(FullHttpRequest request) {
        return requestMethodConfiguration.getNettyMethods().contains(request.method().name());
    }


    @Override
    public void requestHandler(ChannelHandlerContext ctx, FullHttpRequest request) {
        this.doNettyRequest(ctx, request);
    }


    /**
     * 处理netty请求（POST） 解析参数 调用目标方法
     *
     * @param ctx     ctx
     * @param request 请求信息
     */
    private void doNettyRequest(ChannelHandlerContext ctx, FullHttpRequest request) {
        ResponseResult result = new ResponseResult();
        HttpResponseStatus httpStatus = HttpResponseStatus.INTERNAL_SERVER_ERROR;
        FullRequest fullRequestBody = null;
        try {
            //解析内容
            fullRequestBody = this.jsonParamToEntity(request);
            this.setServletFullRequest(request, fullRequestBody);
            HandlerMethod handlerMethod = requestMappingInitialize.getHandlerMapping(fullRequestBody.getApi());
            if (null == handlerMethod) {
                httpStatus = HttpResponseStatus.NOT_FOUND;
                result = ResultUtil.error(CommonEnum.API_NOT_FIND);
                return;
            }
            requestMappingInitialize.getApiCount(fullRequestBody.getApi()).incrementAndGet();
            this.beforeHandlingBusiness(fullRequestBody, handlerMethod);
            // 根据执行目标方法参数类型解析封装
            Object[] args = parameterParsing.parsePackageParameters(handlerMethod, fullRequestBody);
            //设置请求上下文请求参数
            result = (ResponseResult) handlerMethod.getMethod().invoke(handlerMethod.getBean(), args);
            this.afterHandlingBusiness(fullRequestBody, result);
            httpStatus = HttpResponseStatus.OK;
        } catch (Exception e) {
            // 调用invoke执行目标方法 统一处理目标方法抛出的异常和记录日志
            logger.error("has an error:{}, param:{} ", e, JSONObject.toJSONString(request.content().toString(CharsetUtil.UTF_8)));
            Throwable throwable = e instanceof InvocationTargetException ? ((InvocationTargetException) e).getTargetException() : e;
            if (throwable instanceof BaseRuntimeException) {
                httpStatus = HttpResponseStatus.OK;
            }
            result = exceptionResolver.invokeExceptionMethod(throwable);
        } finally {
            //请求结束 清除此线程的请求上下文 释放ThreadLocal
            if (Objects.nonNull(fullRequestBody)) {
                result.setTid(fullRequestBody.getTid());
                AtomicInteger nowCount = requestMappingInitialize.getApiCount(fullRequestBody.getApi());
                if (nowCount != null) {
                    nowCount.decrementAndGet();//计数
                }
            }
            //返回结果
            this.httpResponse(ctx, request, result, httpStatus);
        }
    }


    /**
     * 执行目标方法之前执行
     *
     * @param fullRequestBody 请求信息
     * @param handlerMethod   反射执行的目标方法及声明类
     */
    private void beforeHandlingBusiness(FullRequest fullRequestBody, HandlerMethod handlerMethod) {
        if (!CollectionUtils.isEmpty(iExecuteBeforeAndAfterBusinessProcessors)) {
            iExecuteBeforeAndAfterBusinessProcessors.forEach(iExecuteBeforeBusinessProcessor -> iExecuteBeforeBusinessProcessor.invokeMethodBeforePostProcessor(fullRequestBody, handlerMethod));
        }
    }

    /**
     * 执行目标方法后执行
     *
     * @param result 返回信息
     */
    private void afterHandlingBusiness(FullRequest fullHttpRequest, ResponseResult result) {
        if (!CollectionUtils.isEmpty(iExecuteBeforeAndAfterBusinessProcessors)) {
            for (int i = iExecuteBeforeAndAfterBusinessProcessors.size() - 1; i >= 0; i--) {
                iExecuteBeforeAndAfterBusinessProcessors.get(i).invokeMethodAfterPostProcessor(fullHttpRequest, result);
            }
        }
    }

    /**
     * JSON参数转换实体对象
     *
     * @param request 请求参数
     * @return 转换实体参数对象
     */
    private FullRequest jsonParamToEntity(FullHttpRequest request) {
        FullRequest fullRequest = DefaultParameterConversion.conversion(request);
        MDC.put("tid", fullRequest.getTid());
        logger.info("Api-Info: {}", fullRequest.getApi());
        logger.debug("Request-Parameter :{}", JSONObject.toJSONString(fullRequest));
        return fullRequest;
    }


    /**
     * 设置全局请求参数
     *
     * @param request     httpRequest
     * @param fullRequest 参数
     */
    private void setServletFullRequest(FullHttpRequest request, FullRequest fullRequest) {
        MockHttpServletRequest servletRequest = ServletRequestProcess.createServletRequest(request);
        servletRequest.setAttribute("box", fullRequest);
        RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(servletRequest));
    }


    /**
     * 返回结果
     *
     * @param ctx        ctx
     * @param request    请求
     * @param result     返回数据
     * @param httpStatus 状态
     */
    private void httpResponse(ChannelHandlerContext ctx, FullHttpRequest request, ResponseResult result, HttpResponseStatus httpStatus) {
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, httpStatus,
                Unpooled.copiedBuffer(JSONObject.toJSONString(result, HttpServerHandler.SERIALIZE_CONFIG, SerializerFeature.WriteMapNullValue) + "\r\n", CharsetUtil.UTF_8));
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=UTF-8");
        HttpServerHandler.writeResponse(ctx, request, response);
    }
}
